//
//  ST_PinterestHomeFilterOptionsController.swift
//  btvideo
//
//  Created by mac on 2020/5/29.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import SwifterSwift
import HandyJSON

class ST_PinterestHomeFilterOptionsController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .clear
        
        view.addSubview(root_view)
        root_view.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(16)
            make.top.equalToSuperview().offset(139)
        }
        
        
        root_view.addSubview(close_btn)
        close_btn.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15-(44-28)/2.0)
            make.top.equalToSuperview().offset(22-(44-28)/2.0)
            make.width.height.equalTo(44)
        }
        
        
        
        root_view.addSubview(confirm_btn)
        confirm_btn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-15+(44-28)/2.0)
            make.top.equalToSuperview().offset(22-(44-28)/2.0)
            make.width.height.equalTo(44)
        }
        
        root_view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(close_btn)
        }
        
        
        root_view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.bottom.left.right.equalToSuperview()
            make.top.equalTo(titleLabel.snp.bottom).offset(15)
        }
        
        request_data()
    }
    

//    MARK: - Properties
    fileprivate lazy var root_view:UIView = {
        let control = UIView()
        control.backgroundColor = Color.white
        control.cornerRadius = 16
        return control
    }()

    
    var last_selected_option:PinterestFilterOptionModel!
    
    func request_data(){
        
        self.data_array.removeAll()
        
        self.collectionView.reloadData()
        
        self.titleLabel.text = last_selected_option.keyString
        
        last_selected_index = nil
        JVrequest(PH.recommendSearchChoiceApi, success: { (json) in
        
            print("打印所有选项:",json)
            
            if var list = [PinterestOptionCellModel].deserialize(from: json["data"][self.last_selected_option.remoteKey].arrayObject) as? [PinterestOptionCellModel]{
                
                var all = PinterestOptionCellModel.init()
                
                all.id = "0"
                all.desc = "全部"
                
                list.insert(all, at: 0)
                
                /*
                list = list.map({ (t) -> PinterestOptionCellModel in
                    if !self.canSelected(currModel: t){
                        var a = t
                        let str = "LGBT（即将开放，敬请期待）"
                        a.modifyText(str)
                        return a
                    }else{
                        return t
                    }
                })*/
                
            var array = [PinterestOptionCellModel]()
            
            for (idx,item) in list.enumerated(){
                
                if let selectedId = self.last_selected_option.selectedId,item.id == selectedId{
                    var  a = item
                    a.isSelected = true
                    self.last_selected_index = idx
                    array.append(a)
                }else{
                    array.append(item)
                }
            }
            
           self.data_array = array
            
            self.collectionView.reloadData()
        }
            
        }) { (code, err) in
            
            print("0------,",err)
            
        }
        
        
    }
//    MARK: - Event
    
    var selected_closure:((PinterestFilterOptionModel)->())?
    
    @objc func confirm_click_handle(){
        
        guard let idx = self.last_selected_index else {
            close_click_handle()
            return
        }
        
        let m = self.data_array[idx]
        
        if last_selected_option.selectedId != m.id{
            
            last_selected_option.value = m.desc
            last_selected_option.selectedId = m.id
            
            selected_closure?(last_selected_option)

        }
        
        close_click_handle()
    }
    
    @objc func close_click_handle(){
        
        
        
        self.navigationController?.popViewController(animated: true)
        
    }
    
//    MARK: - Properties

    lazy var close_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("mycenter_icon_返回")!)
        control.addTarget(self, action: #selector(close_click_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    lazy var confirm_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("保存")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        control.setTitleColorForAllStates(UIColor.init(hex: 0xFEC207)!)
        control.addTarget(self, action: #selector(confirm_click_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    lazy var titleLabel:UILabel = {
        let control = UILabel.init()
//        control.text = "向我展示"
        control.textColor = Color.init(hexString: "#333333")
//        control.numberOfLines = 0
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.semibold)
        return control
    }()
    
    
    fileprivate var last_selected_index:Int?
    
    var data_array = [PinterestOptionCellModel]()
    
    lazy var itemWidth:CGFloat = {
        return ScreenWidth
    }()
    
    lazy var itemHeight = 65.cgFloat
    
    lazy var collectionView: UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        
        layout.itemSize = CGSize.init(width: itemWidth, height: itemHeight)
   
        layout.minimumLineSpacing = 0
        //        layout.minimumInteritemSpacing = 14
        
        let bottomEdge = iPhoneXSeries ? BTSafeAreaBottom + 30 : 20 + 20
        
        layout.sectionInset = UIEdgeInsets.init(top: 0, left: 0, bottom: bottomEdge, right: 0)
        
        let collection = UICollectionView(frame: .zero, collectionViewLayout: layout)
        
        collection.register(cellWithClass: ModifyUserItemCell.self)
        
        collection.delegate = self
        
        collection.dataSource = self
        
        collection.alwaysBounceVertical = true
        
        collection.backgroundColor = Color.white
        
        if #available(iOS 11.0, *) {
            collection.contentInsetAdjustmentBehavior = .never
        }
        return collection
    }()
}


extension ST_PinterestHomeFilterOptionsController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
        let cell = collectionView.dequeueReusableCell(withClass: ModifyUserItemCell.self, for: indexPath)
        
        cell.bind(model: data_array[indexPath.row])
        
//        cell.selected_btn.isHidden = !canSelected(currModel: self.data_array[indexPath.row])
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
//        if !canSelected(currModel: self.data_array[indexPath.row]){
//            return
//        }
        
        if indexPath.row != last_selected_index{
            
            if let lastIdx = last_selected_index {
                
                self.data_array[lastIdx].isSelected = false
            }
            
            self.data_array[indexPath.row].isSelected = true
            
            last_selected_index = indexPath.row
            
            self.collectionView.reloadData()
            
        }

    }
    
    
    func canSelected(currModel:PinterestOptionCellModel) -> Bool {
        
        let exist = currModel.desc.lowercased().contains("lgbt")
        
        return !exist
    }

}






struct PinterestOptionCellModel:HandyJSON {
    
    init() {
    }
    
    var id:String = ""
    var desc:String = ""
    
    var isSelected = false
    
    
    mutating func modifyText(_ str:String){
        
        self.desc = str
        
    }
    
}
